package com.vitalgateway.component.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.interceptor.ResponseResult;
import com.vitalgateway.object.exception.SecuritiesBusinessException;
import com.vitalgateway.type.enumerate.ErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

public class CommonForestInterceptor<T> implements Interceptor<T> {
    private final static Logger log = LoggerFactory.getLogger(CommonForestInterceptor.class);
    private final static ThreadLocal<String> THREAD_LOCAL_REQUEST_ID = new ThreadLocal<>();

    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
     *
     * @Param request Forest请求对象
     */
    @Override
    public boolean beforeExecute(ForestRequest req) {
        String requestId = UUID.randomUUID().toString();
        THREAD_LOCAL_REQUEST_ID.set(requestId);
        //打印请求的日志
        log.info("Request id: {},url:{},requestHeader:{},params:{}"
                , requestId, req.getUrl(), JSONObject.toJSONString(req.getHeaders()), JSONObject.toJSONString(req.getArguments()));
        return true;
    }

    @Override
    public ResponseResult onResponse(ForestRequest req, ForestResponse res) {
        String requestId = THREAD_LOCAL_REQUEST_ID.get();
        try {
            if (!res.isSuccess()) {
                log.error("Request id: {},responseCode:{},responseBody:{},costTime:{}ms"
                        , requestId, JSONObject.toJSONString(res.getStatusCode()), res.getContent(), res.getTimeAsMillisecond());
                throw new SecuritiesBusinessException(ErrorCodeEnum.INTERNAL_ERROR);
            } else {
                log.info("Request id: {},responseCode:{},responseBody:{},costTime:{}ms"
                        , requestId, JSONObject.toJSONString(res.getStatusCode()), res.getContent(), res.getTimeAsMillisecond());
            }
        } finally {
            THREAD_LOCAL_REQUEST_ID.remove();
        }
        return Interceptor.super.onResponse(req, res);
    }
}
